<?php
/**
 * 后台会员中心管理
 * @author cjli
 *
 */
class UserAction extends AdminAction
{
	public function _initialize()
	{
		parent::_initialize();
	}
	// 身形信息
        public function measure_info()
        {
           $user_id = intval($_REQUEST['uid']);
           $address_id = intval($_REQUEST['address_id']);
           if($user_id || $address_id)
		   
		   //获取身型字段
           $measure_field = MeasureModel::user_measure_field();
		   $this->assign('measure_field', $measure_field);
		   
		   $measure_infos_field = "";
		   foreach($measure_field as $val){
		       $measure_infos_field .= ','.$val['measure_field'];
		   }
	   	   $where = array();		   
		   if($user_id){
                $where['user_id'] = $user_id;
		   }else{
                $where['address_id'] = $address_id;
		   }
           $measure_infos = M('user_measure')->where($where)->select();
           //var_dump($measure_infos);die;
           //将身形数据转换成数组格式
           if(isset($measure_infos)){
                foreach ($measure_infos as $key => $val) {
                 	$size_edit_measure = D('size_edit_measure')->where(array('measure_id' => $val['id']))->order('id desc')->select();
                 	$measure_infos[$key]['is_edit_new'] = 0;
                    foreach($size_edit_measure as $v){
                    	$v['data'] = unserialize($v['data']);
                    	$v['data']['edit_time'] = $v['edit_time'];
                    	$v['data']['type'] = $v['type'];
                        $measure_infos[$key]['edit_data'][] = $v['data'];
                        if((time()-$v['edit_time'])<3600*24*7){
                        	$measure_infos[$key]['is_edit_new'] = 1;
                        }
                    }
                }
				
                 //用户信息
                 $userInfo = UserModel::getUserInfo($user_id);
                 $this->assign('user', $userInfo);
                
                 $this->assign('measure_infos',$measure_infos);
                 $this->display('measure_info');
            }else{
                //如果该用户没有填写过身形数据
                   $this->display('measure_info'); 
            }  
        }
        
        
	//会员列表
	public function user_list()
	{
		$searchTypeArray = array(
			'0' => 'users.email',
			'1' => 'users.username',
		);
		
		//搜索
		$where = array();
		if($_REQUEST['partner'] == 1){
			$where['is_partner'] = 1;
		}else{
			$where['is_partner'] = 0;
		}
		if(isset($_POST['keyword']) && $_POST['keyword']){
			$searchtype = $searchTypeArray[intval($_POST['searchtype'])];
			$where[$searchtype] = array('like','%'.trim($_POST['keyword']).'%');
		}
		if(isset($_POST['rank_id']) && intval($_POST['rank_id'])){
			$where['rank_id'] = intval($_POST['rank_id']);
		}
		if(isset($_POST['is_designer']) && $_POST['is_designer'] != -1){
			$where['is_designer'] = intval($_POST['is_designer']);
		}

		$pageRows = 20;
		if(isset($_REQUEST['pageRows']) && intval($_REQUEST['pageRows'])){
			$pageRows = intval($_REQUEST['pageRows']);
		}
		$user_db = D('users');
		$user_db->where($where);
		$count = $user_db->count();//总记录数
		import("ORG.Util.Page");// 导入分页类
		$Page = new Page($count, $pageRows);// 实例化分页类 传入总记录数和每页显示的记录数
		$pageShow = $Page->show();// 分页显示输出
		$this->assign('pageShow', $pageShow);
		
		//用户列表
		$user_db->field('users.*,user_rank.name as rank_name');
		$user_db->join('user_rank ON user_rank.id = users.rank_id');
		$user_db->limit($Page->firstRow.','.$Page->listRows);
		$user_db->order('users.id desc');
		$user_db->where($where);
        //var_dump($where);die;
		$userList = $user_db->select();
        foreach ($userList as $key=>$val){
            $userList[$key]['cart_num'] = D('cart_products')->where('user_id='.$val['id'])->getField('sum(qty)');
        }
		$this->assign('userList', $userList);
                
        $lang_db = D('language');
        $languageArray = $lang_db->field('id,name')->where('status=1')->order('listorder DESC')->select();
        if($languageArray){
            foreach ($languageArray as $lang){
                $languageList[$lang['id']] = $lang;
            }
        }
        $this->assign('languageList',$languageList);
		
		$rankList = UserModel::getRankList();
		$this->assign('rankList', $rankList);
		
		$this->assign('search', $_POST ? $_POST : null);
		$this->display('user_list');
	}
	
	//添加会员
	public function user_add()
	{
		if(isset($_POST['dosubmit'])){
			$user_db = D('Users');
			$auto = array(
				array('login_count','0'),
				array('login_ip','get_client_ip',3,'function'),
				array('login_time','time',3,'function'),
				array('reg_time','time',1,'function'),
			);
			$user_db->setProperty("_auto",$auto); //自动填充
			
			if($_POST['is_designer'] && empty($_POST['nickname'])){
				$this->error('设计师的名称不能为空！', U('user/user_add'));
			}
			
			$_POST['language_id'] = C('language_id');
			list($_POST['password'],$_POST['rand_salt']) = UserModel::generatePassword($_POST['password']);
			
			if ( (isset($_FILES['up_user_photo']) && $_FILES['up_user_photo']['tmp_name']) || ( isset($_FILES['up_user_designer_logo']) && $_FILES['up_user_designer_logo']['tmp_name']) || (isset($_FILES['up_user_designer_adv']) && $_FILES['up_user_designer_adv']['tmp_name'])){
			$info = $this->upload('user');
			if(is_array($info)) {// 上传成功 获取上传文件信息
				if(isset($info['up_user_photo'])){
					$_POST['user_photo'] = UPLOAD_PATH . $info['up_user_photo']['savename'];
				}
				if(isset($info['up_user_photo'])){
					$_POST['user_designer_logo'] = UPLOAD_PATH . $info['up_user_designer_logo']['savename'];
				}
				if(isset($info['up_user_designer_adv'])){
					$_POST['user_designer_adv'] = UPLOAD_PATH . $info['up_user_designer_adv']['savename'];
				}
			}else{
				$this->error($info);
			}
		}
			
			$user_db->create();
			$user_id = $user_db->add();
			$gotoUrl = $_REQUEST['is_partner'] == 1 ? U('user/partner') : U('user/user_list');
			if($user_id){
				$this->insert_designer($user_id, $_POST);
//				$rank_point = $_POST['rank_points'];
//				UserModel::updateUserRank($user_id, $rank_point); //更新会员等级
				$this->success('会员添加成功！', $gotoUrl);
			}else{
				$this->error('会员添加失败！', $gotoUrl);
			}
		}else{
			$rankList = UserModel::getRankList();
			$this->assign('rankList', $rankList);
//			$countryList = SiteModel::getCountryList();
//			$this->assign('countryList', $countryList);
			$this->display('user_form');
		}
	}
	
	//编辑会员
	public function user_edit()
	{
		$user_id = intval($_GET['uid']);
		$user_db = D('users');
		$userInfo = UserModel::getUserInfo($user_id);
		if(!$userInfo){
			$this->error('会员不存在！', U('user/user_list'));
		}	
		if(isset($_POST['dosubmit'])){
//			$auto = array(
//				array('login_ip','get_client_ip',3,'function'),
//				array('login_time','time',3,'function'),
//			);
//			$user_db->setProperty("_auto",$auto); //自动填充
			//修改密码
			if($_POST['password'] && $_POST['pwdconfirm'] && $_POST['password'] == $_POST['pwdconfirm']){
				list($_POST['password'],$_POST['rand_salt']) = UserModel::generatePassword($_POST['password'], $userInfo['rand_salt']);
			}else{
				unset($_POST['password']);
			}
			
			if($_POST['is_designer'] && empty($_POST['nickname'])){
				$this->error('设计师的名称不能为空！', U('user/user_edit', array('uid' => $user_id)));
			}
			
		if ( (isset($_FILES['up_user_photo']) && $_FILES['up_user_photo']['tmp_name']) || ( isset($_FILES['up_user_designer_logo']) && $_FILES['up_user_designer_logo']['tmp_name']) || (isset($_FILES['up_user_designer_adv']) && $_FILES['up_user_designer_adv']['tmp_name'])){
			$info = $this->upload('user');
			if(is_array($info)) {// 上传成功 获取上传文件信息
				if(isset($info['up_user_photo'])){
					$_POST['user_photo'] = UPLOAD_PATH . $info['up_user_photo']['savename'];
				}
				if(isset($info['up_user_photo'])){
					$_POST['user_designer_logo'] = UPLOAD_PATH . $info['up_user_designer_logo']['savename'];
				}
				if(isset($info['up_user_designer_adv'])){
					$_POST['user_designer_adv'] = UPLOAD_PATH . $info['up_user_designer_adv']['savename'];
				}
			}else{
				$this->error($info);
			}
		}
			
			$user_db->create();
			$user_db->where('id='.$user_id);
			$user_db->save();
			
			$this->insert_designer($user_id, $_POST);

//			$rank_point = $_POST['rank_point'];
//			UserModel::updateUserRank($uid, $rank_point); //更新会员等级
			$gotoUrl = $_REQUEST['is_partner'] == 1 ? U('user/partner') : U('user/user_list');
			$this->success('会员编辑成功！', $gotoUrl);
		}else{
			$rankList = UserModel::getRankList();
			$this->assign('rankList', $rankList);
//			$countryList = SiteModel::getCountryList();
//			$this->assign('countryList', $countryList);
//			$provinceList = null;
//			if($user['country_id']){
//				$provinceList = $this->public_area_ajax($user['country_id'],0);
//			}
//			$this->assign('provinceList', $provinceList);
			if($userInfo['is_designer']){
				$userInfo['designer'] = UserModel::getUserDesignerInfo($user_id);
			}

			$this->assign('user', $userInfo);
			$this->display('user_form');
		}
	}
	
	/**
	 * 添加设计师资料
	 * @param int $user_id 用户ID
	 * @param array $post post数组
	 */
	private function insert_designer($user_id, $post)
	{
		$designer_db = D('user_designer');
		$designer_db->where('user_id='.$user_id)->delete();

		if(!(isset($post['is_designer']) && $post['is_designer'])){
			return false;
		}
		$data = array(
			'user_id' => $user_id,
			'user_designer_logo' => $post['user_designer_logo'],
			'user_designer_adv' => $post['user_designer_adv'],
			'user_content' => trim($post['user_content']),
			'user_description' => trim($post['user_description'])
		);
		$designer_db->add($data);
	}
	
	//删除会员
	public function user_delete()
	{
		$uid = intval($_GET['uid']);
		$user_db = M('User');
		$userInfo = UserModel::getUserInfo($uid);
		if(!$userInfo){
			$this->error('会员不存在！', U('user/user_list'));
		}
		$user_db->delete($uid);
		$user_address_db = D('user_adress');
		$user_address_db->where(array('user_id' => $uid))->delete();
		$this->success('会员删除成功！', U('user/user_list'));
	}
	//导出用户列表
	public function user_list_export()
	{
		import('COM.XmlExcel');
		$excel=new XmlExcel;
    	$excel_title= array('邮箱','使用语言','注册日期');
    	$excel->addHead($excel_title); //设置CSV文件标题
    
    	$user_db = D('users');
		$usersList = $user_db->order('reg_time desc')->select();
		
		foreach($usersList as $key =>$value){
			$language = D('language')->where(array('id'=>$value['language_id']))->getField('name');
			$addRowData = array(
				$value['email'],
				$language,
				date('Y-m-d H:i:s',$value['reg_time'])				
			);
			$excel->addRow($addRowData);
		}

		$excel->export('user_message');
	}
	/**
	 * 导出合作伙伴客户信息
	 * */
	public function user_address_list_export()
	{
	    import('COM.XmlExcel');
	    $excel=new XmlExcel;
	    $excel_title= array('姓名','手机号','合作伙伴账户');
	    $excel->addHead($excel_title); //设置CSV文件标题
	
	    $user_db = D('user_address');
	    $usersList = $user_db->query('select a.delivery_first_name,a.delivery_phone,b.email from user_address a,users b where a.user_id=b.id');
	
	    foreach($usersList as $key =>$value){
	        $addRowData = array(
	            $value['delivery_first_name'],
	            $value['delivery_phone'],
	            $value['email']
	        );
	        $excel->addRow($addRowData);
	    }
	
	    $excel->export('user_message');
	}
	//配货地址管理
	public function address_list()
	{
		$uid = intval($_GET['uid']);
		$addressList = UserModel::getAddressList($uid);
		$this->assign('addressList', $addressList);
		$userInfo = UserModel::getUserInfo($uid);
		$this->assign('user', $userInfo);
		$this->display('address_list');
	}
	
	//账户明细
	public function account_log_list()
	{
		$uid = intval($_GET['uid']);
		$userInfo = UserModel::getUserInfo($uid);
		if(!$userInfo){
			$this->error('会员不存在！', U('user/user_list'));
		}
		$user_account_db = D('user_account_log');
		$user_account_db->where('user_id='. $uid);
		$count = $user_account_db->count();
		
		$pageRows = 20;
		if(isset($_REQUEST['pageRows']) && intval($_REQUEST['pageRows'])){
			$pageRows = intval($_REQUEST['pageRows']);
		}
			
		import("ORG.Util.Page");
		$Page = new Page($count, $pageRows);
		$pageShow = $Page->show();
		$this->assign('pageShow', $pageShow);
		
		$user_account_db->where('user_id='. $uid);
		$user_account_db->limit($Page->firstRow.','.$Page->listRows);
		$logList = $user_account_db->order('id DESC')->select();
		$this->assign('logList', $logList);
		$this->assign('user', $userInfo);
		$this->display('account_log_list');
	}
	
	//调节账户
	public function account_log_add()
	{
		$uid = intval($_GET['uid']);
		$userInfo = UserModel::getUserInfo($uid);
		if(!$userInfo){
			$this->error('会员不存在！', U('user/user_list'));
		}
		if($_POST['dosubmit']){
			/* 提交值 */
	    $change_desc    = trim($_POST['change_desc']);
	    $user_money     = floatval($_POST['add_sub_user_money']) * abs(floatval($_POST['user_money']));
	    $frozen_money   = floatval($_POST['add_sub_frozen_money']) * abs(floatval($_POST['frozen_money']));
	    $rank_points    = floatval($_POST['add_sub_rank_points']) * abs(floatval($_POST['rank_points']));
	    $pay_points     = floatval($_POST['add_sub_pay_points']) * abs(floatval($_POST['pay_points']));
	    
	    if ($user_money == 0 && $frozen_money == 0 && $rank_points == 0 && $pay_points == 0)
	    {
	        $this->error('没有调节账户信息！', U('user/account_log_list', 'uid='.$uid));
	    }

	    /* 保存 */
		UserModel::user_account_change($uid, $user_money, $frozen_money, 1, NULL, $change_desc, NULL);
	    UserModel::logAccountChange($uid, $user_money, $frozen_money, $rank_points, $pay_points, $change_desc, UserModel::ACT_ADJUSTING);
	    $this->success('添加成功！', U('user/account_log_list', 'uid='.$uid));
		}else{
			$this->assign('user', $userInfo);
			$this->display('account_log_add');
		}
	}
	
	//充值和提现申请
	public function account_list()
	{
		$where = array();
		if(isset($_POST['process_type']) && $_POST['process_type']>=0){
			$where['process_type'] = $_POST['process_type'];
		}
		if(isset($_POST['is_paid']) && $_POST['is_paid']>=0){
			$where['is_paid'] = $_POST['is_paid'];
		}
		if(isset($_POST['user_name']) && $_POST['user_name']){
			$user_db = D('users');
			$user_id = $user_db->where( array('username' => $_POST['user_name']))->getField('id');
			if($user_id){
				$where['user_id'] = $user_id;
			}
		}
		if(isset($_POST["recharge_id"]) && $_POST["recharge_id"]){
			$recharge_id = trim($_POST["recharge_id"]);
			if('recharge_' == substr($recharge_id,0,9) && is_numeric($account_id = substr($recharge_id,9))){
				$where['user_account.id'] = $account_id;
			}
		}

		$pageRows = 20;
			if(isset($_REQUEST['pageRows']) && intval($_REQUEST['pageRows'])){
				$pageRows = intval($_REQUEST['pageRows']);
			}
			
		$user_account_db = D('user_account');
		$user_account_db->where($where);
		$count = $user_account_db->count();
		import("ORG.Util.Page");
		$Page = new Page($count, $pageRows);
		$pageShow = $Page->show();
		$this->assign('pageShow', $pageShow);
		
		$user_account_db->field('user_account.*, users.username');
		$user_account_db->join('`users` ON users.id=user_account.user_id');
		$user_account_db->limit($Page->firstRow.','.$Page->listRows);
		$user_account_db->where($where);
		$accountList = $user_account_db->select();
		$this->assign('accountList', $accountList);
		
		$this->display('account_list');
	}
	//添加充值和提现申请
	public function account_add()
	{
		if(isset($_POST['dosubmit'])){
			/* 初始化变量 */
	    $is_paid      = !empty($_POST['is_paid'])      ? intval($_POST['is_paid'])        : 0;
	    $amount       = !empty($_POST['amount'])       ? floatval($_POST['amount'])       : 0;
	    $process_type = !empty($_POST['process_type']) ? intval($_POST['process_type'])   : 0;
	    $user_name    = !empty($_POST['user_name'])    ? trim($_POST['user_name'])        : '';
	    $admin_note   = !empty($_POST['admin_note'])   ? trim($_POST['admin_note'])       : '';
	    $user_note    = !empty($_POST['user_note'])    ? trim($_POST['user_note'])        : '';
	    $payment      = !empty($_POST['payment'])      ? trim($_POST['payment'])          : '';
	    
	    $user_db = D('users');
			$userInfo = $user_db->field('id,user_money')->where(array('username' => $user_name))->find();
			if(!$userInfo){
				$this->error('会员不存在！', U('user/account_list'));
			}
			/* 退款，检查余额是否足够 */
	    if ($process_type == 1 && $amount > $userInfo['user_money'])
	    {
	       $this->error('退款失败，退款金额大于用户余额！', U('user/account_add'));
	    }
			/* 入库的操作 */
      if ($process_type == 1)
      {
      	$amount = (-1) * $amount;
      }
      $data = array(
      	'user_id' => $userInfo['id'],
      	'admin_user' => $_SESSION['admin_user_info']['user_name'],
      	'is_paid' => $is_paid,
      	'amount' => $amount,
	      'process_type' => $process_type,
	      'admin_note' => $admin_note,
	      'user_note' => $user_note,
	      'payment' => $payment,
	      'add_time' => time(),
      	'paid_time' => time(),
      );
      
			$user_account_db = D('user_account');
			$lastId = $user_account_db->add($data);
			if($lastId){
				//完成操作直接修改会员金额
				if($is_paid == 1){
					UserModel::logAccountChange($userInfo['id'],$amount,0,0,0,'', $process_type ? UserModel::ACT_DRAWING : UserModel::ACT_SAVING);
				}
				$this->success('申请成功！', U('user/account_list'));
			}else{
				$this->error('申请失败！', U('user/account_list'));
			}
		}else{
			$paymentList = PaymentModel::getPaymentList();
			$this->assign('paymentList', $paymentList);
			$this->display('account_form');
		}
	}
	//编辑充值和提现申请
	public function account_edit()
	{
		$aid = intval($_GET['aid']);
		$user_account_db = D('user_account');
		$user_account_db->field('user_account.*,users.username');
		$user_account_db->join('`users` ON users.id = user_account.user_id');
		$accountInfo = $user_account_db->where('user_account.id='.$aid)->find();

		if(isset($_POST['dosubmit'])){
			if($accountInfo['is_paid'] == 1){
				$this->error('已经完成禁止修改', U('user/account_list'));
			}
			/* 初始化变量 */
	    $is_paid      = !empty($_POST['is_paid'])      ? intval($_POST['is_paid'])        : 0;
	    $amount       = !empty($_POST['amount'])       ? floatval($_POST['amount'])       : 0;
	    $process_type = !empty($_POST['process_type']) ? intval($_POST['process_type'])   : 0;
	    $user_id    	= !empty($_POST['user_id'])    	 ? intval($_POST['user_id'])        : '';
	    $admin_note   = !empty($_POST['admin_note'])   ? trim($_POST['admin_note'])       : '';
	    $user_note    = !empty($_POST['user_note'])    ? trim($_POST['user_note'])        : '';
	    $payment      = !empty($_POST['payment'])      ? trim($_POST['payment'])          : '';
	    
	    $user_db = D('users');
			$user_money = $user_db->where('id='.$user_id)->getField('user_money');
			if(!$user_money){
				$this->error('会员不存在！', U('user/account_list'));
			}
			/* 退款，检查余额是否足够 */
	    if ($process_type == 1 && $amount > $user_money)
	    {
	       $this->error('退款失败，退款金额大于用户余额！', U('user/account_list'));
	    }
			/* 入库的操作 */
      if ($process_type == 1)
      {
      	$amount = (-1) * $amount;
      }
      $data = array(
      	'user_id' => $user_id,
      	'admin_user' => $_SESSION['admin_user_info']['user_name'],
      	'is_paid' => $is_paid,
      	'amount' => $amount,
	      'process_type' => $process_type,
	      'admin_note' => $admin_note,
	      'user_note' => $user_note,
	      'payment' => $payment,
      	'paid_time' => time(),
      );
			
			$user_account_db->where('id='.$aid)->save($data);
			
			//完成操作直接修改会员金额
			if($is_paid == 1){
				UserModel::logAccountChange($userInfo['id'],$amount,0,0,0,'', $process_type ? UserModel::ACT_DRAWING : UserModel::ACT_SAVING);
			}
				
			$this->success('修改申请成功！', U('user/account_list'));
		}else{

			$paymentList = PaymentModel::getPaymentList();
			$this->assign('paymentList', $paymentList);
			$this->assign('account', $accountInfo);
			$this->display('account_form');
		}
	}
	
	//资金管理
	public function account_manage()
	{
		//TODO
	}
	
	//会员等级列表
	public function rank_list()
	{
		$rankList = UserModel::getRankList();
		$this->assign('rankList', $rankList);
		$this->display('rank_list');
	}
	
	//添加会员等级
	public function rank_add()
	{
		if(isset($_POST['dosubmit'])){
			$rank_db = D('user_rank');
			$rank_db->create();
			$rankId = $rank_db->add();
			if($rankId){
				S('user_rank_list', NULL);
				$this->success('会员等级添加成功！', U('user/rank_list'), false, 'add');
			}else{
				$this->error('会员等级添加失败！', U('user/rank_list'), false, 'add');
			}
		}else{
			$this->display('rank_form');
		}
	}
	
	//编辑会员等级
	public function rank_edit()
	{
		$rid = intval($_GET['rid']);
		$rank_db = D('user_rank');
		$rankList = UserModel::getRankList();
		if(!$rankList[$rid]){
			$this->error('会员等级不存在！', U('user/rank_list'), false, 'edit');
		}
		if(isset($_POST['dosubmit'])){
			$rank_db->create();
			$rank_db->save();
			S('user_rank_list', NULL);
			$this->success('会员等级编辑成功！', U('user/rank_list'), false, 'edit');
		}else{
			$this->assign('rank', $rankList[$rid]);
			$this->display('rank_form');
		}
	}
	
	//删除会员等级
	public function rank_delete()
	{
		$rid = intval($_GET['rid']);
		$rank_db = D('user_rank');
		$rankList = UserModel::getRankList();
		if(!$rankList[$rid]){
			$this->error('会员等级不存在！', U('user/rank_list'));
		}
		$rank_db->delete($rid);
		S('user_rank_list', NULL);
		$this->success('删除成功！', U('user/rank_list'));
	}
	
	//邮件模板列表
	public function tpl_list()
	{
		$tpldb = D('email_template');
		$tplList = $tpldb->select();
		$this->assign('tplList', $tplList);
		$this->display('tpl_list');
	}
	
	//邮件模板添加
	public function tpl_add()
	{
		if(isset($_POST['dosubmit'])){
			$tpl_db = D('email_template');
			$tpl_id = SiteModel::updateEmailTemplate($_POST);
			if($tpl_id){
				SiteModel::updateEmailTemplateItems($_POST['tpl'], $tpl_id);
				S('email_template_list', NULL);
				$this->success('模板添加成功！', U('user/tpl_list'));
			}else{
				$this->error('模板添加失败！', U('user/tpl_list'));
			}
		}else{
			$this->display('tpl_form');
		}
	}
	
	//编辑邮件模板
	public function tpl_edit()
	{
		$tpl_id = intval($_GET['tpl_id']);
		$tpl_db = D('email_template');
		$tplInfo = $tpl_db->find($tpl_id);
		if(!$tplInfo){
			$this->error('邮件模板不存在!', U('user/tpl_list'));
		}
		if(isset($_POST['dosubmit']))
		{
			$tpl_id = SiteModel::updateEmailTemplate($_POST, $tpl_id);
			if($tpl_id){
				SiteModel::updateEmailTemplateItems($_POST['tpl'], $tpl_id);
			}
			S('email_template_list', NULL);
			$this->success('模板编辑成功！', U('user/tpl_list'));
		}else{
			$tplInfo['items'] = SiteModel::getEmailTemplateItems($tpl_id);
			$this->assign('tpl', $tplInfo);
			$this->display('tpl_form');
		}
	}
	
	//删除邮件模板
	public function tpl_delete()
	{
		$tpl_id = intval($_GET['tpl_id']);
		$tpl_db = D('email_template');
		$tplInfo = $tpl_db->find($tpl_id);
		if(!$tplInfo){
			S('email_template_list', NULL);
			$this->error('邮件模板不存在！', U('user/tpl_list'));
		}
		$tpl_db->delete($tpl_id);
		$tpli_db = D('email_template_items');
		$tpli_db->where('email_template_id='.$tpl_id)->delete();
		$this->success('邮件模板删除成功！', U('user/tpl_list'));
	}
	
	//邮件订阅
	public function registry_list()
	{
		$pageRows = 20;
		if(isset($_REQUEST['pageRows']) && intval($_REQUEST['pageRows'])){
			$pageRows = intval($_REQUEST['pageRows']);
		}
			
		$email_db = D('email_registry');
		$email_db->where($where);
		$count = $email_db->count();//总记录数
		import("ORG.Util.Page");// 导入分页类
		$Page = new Page($count, $pageRows);// 实例化分页类 传入总记录数和每页显示的记录数
		$pageShow = $Page->show();// 分页显示输出
		$this->assign('pageShow', $pageShow);
		//用户列表
		$email_db->limit($Page->firstRow.','.$Page->listRows);
		$emailList = $email_db->order('id desc')->select();
		$this->assign('emailList', $emailList);
		$this->display('registry_list');
	}
	
	//邮件发送
	public function registry_send()
	{
		if(isset($_POST['dosubmit'])){
			$title = $_POST['title'];
			$content = $_POST['content'];
			$mailInstance = D(WEB_APP_NAME.'://Email');
			$email_db = D('email_registry');
			$emailList = $email_db->field('email')->where('status=1')->select();
			if($emailList){
				foreach ($emailList as $email){
					$mailInstance->sendMail($email['email'], $title, $content);
				}
			}
			$this->success('已经发送', U('user/registry_list'), 'send');
		}else{
			$this->display('registry_send');
		}
	}
	
	//邮件导出为CSV
	public function registry_export()
	{
		import('COM.XmlExcel');
		$excel=new XmlExcel;
        $excel_title= array('email','时间','状态');
        $excel->addRow($excel_title); //设置CSV文件标题

        $email_db = D('email_registry');
		$emailList = $email_db->order('id desc')->field("email,from_unixtime(time) as time,status")->select();
        foreach($emailList as $k=>$v){
            if($v['time'] == '1970-01-01 08:00:00'){
                $v['time'] = '';
            }
            $excel->addRow($v);
        }
		$excel->export('email_registry');
	}
	
	//删除订阅邮件
	public function registry_delete()
	{
		$ids = $_POST['ids'];
		if(!empty($ids)){
			$ids = implode(',', $ids);
			$email_db = D('email_registry');
			$email_db->delete($ids);
		}
		redirect(U('user/registry_list'));
	}
	
	/**
	 * ajax 获取地区
	 * @param int $pid //国家ID
	 * @param int $is_ajax //是否ajax调用1是,0否
	 */
	public function public_area_ajax($pid = 0, $is_ajax = 1)
	{
		if($pid == 0){
			$pid = $_GET['pid'];
		}
		$pid = intval($pid);
		if(!$pid) exit('-1');
		$areaList = SiteModel::get_area_list($pid);
		if($is_ajax){
			if(is_null($areaList)) exit('-1');
			else	echo json_encode($areaList);exit;
		}else{
			return $areaList;
		}
	}
	
	//检测用户名是否存在
	public function public_checkname_ajx()
	{
		$name = trim($_GET['username']);
		$user_id = intval($_GET['uid']);
		$where['username'] = $name;
		if($user_id){
			$where['id'] = array('neq', $user_id);
		}
		$user_db = D('users');
		$count = $user_db->where($where)->count();
		if($count){
			exit('0');
		}
		exit('1');
	}
	
	//检测邮件模板标识是否存在
	public function check_email_template_ajax()
	{
		$path_alias = trim($_GET['path_alias']);
		$where['path_alias'] = $path_alias;
		$tpl_db = D('email_template');
		$count = $tpl_db->where($where)->count();
		if($count){
			exit('0');
		}
		exit('1');
	}
    
    //未使用注册红包用户的邮箱 执行完可删除
	public function no_register_bouns(){

		    //获取身型字段
		    $where['_string'] = " ub.bonus_id=3  and ub.used_time=0 ";
            $res = D('user_bonus as ub')->field('ub.user_id,u.email')
					->join('users as u on(u.id = ub.user_id)')
					->where($where)->select();
			
			import('COM.XmlExcel');
			$excel=new XmlExcel;
			// $excel_title= array();
			// $excel->addHead($excel_title); 

            foreach($res as $val){
                $addRowData = array(
                    $val['email'],
                	);
		    	$excel->addRow($addRowData);	
	    	}
    
		    $excel_name = '未使用注册红包用户的邮箱'.'-'.date('Y-m-d H:i');
			$excel->export($excel_name);
			exit;
        }

    //执行套装附加裤子价格 执行完可删除
	public function pants_price_add(){
            
            $pantsArr = array(
                'U4001' => 888,'U4021' => 888,'U4041' => 199,'U4061' => 109,'U4081' => 119,
                'U4002' => 888,'U4022' => 109,'U4042' => 199,'U4062' => 109,'U4082' => 119,
                'U4003' => 119,'U4023' => 109,'U4043' => 199,'U4063' => 109,'U4083' => 888,
                'U4004' => 888,'U4024' => 888,'U4044' => 888,'U4064' => 89, 'U4084' => 888,
                'U4005' => 139,'U4025' => 109,'U4045' => 199,'U4065' => 89, 'U4085' => 119,
                'U4006' => 119,'U4026' => 109,'U4046' => 299,'U4066' => 89,
                'U4007' => 119,'U4027' => 109,'U4047' => 299,'U4067' => 89,
                'U4008' => 119,'U4028' => 109,'U4048' => 299,'U4068' => 109,
                'U4009' => 888,'U4029' => 109,'U4049' => 119,'U4069' => 888,
                'U4010' => 119,'U4030' => 109,'U4050' => 888,'U4070' => 119,
                'U4011' => 119,'U4031' => 109,'U4051' => 888,'U4071' => 888,
                'U4012' => 119,'U4032' => 119,'U4052' => 888,'U4072' => 119,
                'U4013' => 119,'U4033' => 119,'U4053' => 888,'U4073' => 119,
                'U4014' => 888,'U4034' => 888,'U4054' => 119,'U4074' => 119,
                'U4015' => 119,'U4035' => 199,'U4055' => 888,'U4075' => 119,
                'U4016' => 119,'U4036' => 199,'U4056' => 89, 'U4076' => 119,
                'U4017' => 119,'U4037' => 199,'U4057' => 89, 'U4077' => 888,
                'U4018' => 109,'U4038' => 299,'U4058' => 89, 'U4078' => 888,
                'U4019' => 109,'U4039' => 259,'U4059' => 888,'U4079' => 119,
                'U4020' => 119,'U4040' => 199,'U4060' => 888,'U4080' => 119,
            	);
            
            foreach ($pantsArr as $key => $val) {
            	if($val == 888){
            		continue;
            	}
	            $sql = "select product.id as product_id,product.model_id,s.suppliers_id,s.suppliers_name from suppliers as s join product as product on(product.suppliers_id = s.suppliers_id) where product.model_id in(2,18) and s.suppliers_name = '".$key."'";
				$res = M()->query($sql);
				foreach ($res as $k => $v) {
					$saveData = array(
                        'add_more'    => 1,
                        'pants_price' => $val,
						);
				    $editRes = M('product')->where(array('id' => $v['product_id']))->save($saveData);
				    $res[$k]['edit'] = $editRes;
				}
				echo "<pre />";
			    print_r($res);
            }
        }


    //团单页面
	public function wedding_group(){
		$where = array();

		$pageRows = 20;
		if(isset($_REQUEST['pageRows']) && intval($_REQUEST['pageRows'])){
			$pageRows = intval($_REQUEST['pageRows']);
		}
		
		$wedding_msg_db = D('wedding_msg');
		$wedding_msg_db->where($where);
		$count = $wedding_msg_db->count();//总记录数
		import("ORG.Util.Page");// 导入分页类
		$Page = new Page($count, $pageRows);// 实例化分页类 传入总记录数和每页显示的记录数
		$pageShow = $Page->show();// 分页显示输出
		$this->assign('pageShow', $pageShow);
		//用户列表
		$wedding_msg_db->limit($Page->firstRow.','.$Page->listRows);
		$wedding_msg_db->where($where);
		$wedding_msg_db->order('id desc');
		$list = $wedding_msg_db->select();
		
		$this->assign('list', $list);
		$this->display('wedding_group');
    }
 
 	public function wedding_group_info()
	{
		$id = intval($_GET['id']);
		$wedding_msg_db = D('wedding_msg');
		$msgInfo = $wedding_msg_db->find($id);
	
		$this->assign('msgInfo', $msgInfo);
		$this->display('wedding_group_info');
	}

	//合作伙伴
	public function partner()
	{
		$searchTypeArray = array(
			'0' => 'users.email',
			'1' => 'users.username',
		);
		
		//搜索
		$where = array();
        $where['is_partner'] = 1;
		
		if(isset($_POST['keyword']) && $_POST['keyword']){
			$searchtype = $searchTypeArray[intval($_POST['searchtype'])];
			$where[$searchtype] = array('like','%'.trim($_POST['keyword']).'%');
		}
		if(isset($_POST['rank_id']) && intval($_POST['rank_id'])){
			$where['rank_id'] = intval($_POST['rank_id']);
		}
		if(isset($_POST['is_designer']) && $_POST['is_designer'] != -1){
			$where['is_designer'] = intval($_POST['is_designer']);
		}

		$pageRows = 20;
		if(isset($_REQUEST['pageRows']) && intval($_REQUEST['pageRows'])){
			$pageRows = intval($_REQUEST['pageRows']);
		}
		$user_db = D('users');
		$user_db->where($where);
		$count = $user_db->count();//总记录数
		import("ORG.Util.Page");// 导入分页类
		$Page = new Page($count, $pageRows);// 实例化分页类 传入总记录数和每页显示的记录数
		$pageShow = $Page->show();// 分页显示输出
		$this->assign('pageShow', $pageShow);
		
		//用户列表
		$user_db->field('users.*,user_rank.name as rank_name');
		$user_db->join('user_rank ON user_rank.id = users.rank_id');
		$user_db->limit($Page->firstRow.','.$Page->listRows);
		$user_db->order('users.id desc');
		$user_db->where($where);
        //var_dump($where);die;
		$userList = $user_db->select();
        foreach ($userList as $key=>$val){
            $userList[$key]['user_count'] = D('user_address')->where('user_id='.$val['id'])->count();
            $userList[$key]['order_count'] = D('orders')->where('user_id='.$val['id'])->count();
        }
		$this->assign('userList', $userList);
                
        $lang_db = D('language');
        $languageArray = $lang_db->field('id,name')->where('status=1')->order('listorder DESC')->select();
        if($languageArray){
            foreach ($languageArray as $lang){
                $languageList[$lang['id']] = $lang;
            }
        }
        $this->assign('languageList',$languageList);
		
		$rankList = UserModel::getRankList();
		$this->assign('rankList', $rankList);
		
		$this->assign('search', $_POST ? $_POST : null);
		$this->display('partner');
	}

	//合作伙伴 之 客户信息管理
	public function partner_address_list()
	{
		$uid = intval($_GET['uid']);
		$addressList = UserModel::getAddressList($uid);
		$this->assign('addressList', $addressList);
		$userInfo = UserModel::getUserInfo($uid);
		$this->assign('user', $userInfo);
		$this->display('partner_address_list');
	}

	//身型照片设置
	public function measure_photo()
	{
		$mid   = intval($_REQUEST['mid']);
		$where = array();		   
		$where['id'] = $mid;
		if(isset($_POST['dosubmit']))
		{
			$post = array();
			$info = $this->upload('measure/'.date('Y/m/d', time()));
			if($info){
				//侧面照片
				if (isset($_FILES['front_img']) && $_FILES['front_img']['name']){
					$post['front_img'] = UPLOAD_PATH . $info['front_img']['savename'];
				}
				//侧面照片
				if (isset($info['side_img']) && $_FILES['side_img']['name']){
					$post['side_img'] = UPLOAD_PATH.$info['side_img']['savename'];		
				}
			}else{
				$this->error($info);
			}
			if($post){
				$measure = M('user_measure')->where($where)->save($post);
			}
		}
		
		$measure = M('user_measure')->where($where)->find();
		$this->assign('measure', $measure);		
		$this->display('measure_photo');
	}
	//转移合作伙伴的地址信息
	public function move_user_address(){
        $roleid = $_SESSION['admin_user_info']['roleid'];
        if($roleid !=1 ){
            $result['status']=0;
            $result['msg']="只有超级管理员才能转移！";
            echo json_encode($result);
            exit;
        }
        $userId	= I("get.user_id","","intval");
	    $userInfo = M("users")->where(['id'=>$userId])->find();
	    if(empty($userInfo) || $userInfo['is_partner']!=1){
            $result['status']=0;
            $result['msg']="非法参数！";
            echo json_encode($result);
            exit;
        }
        $userEmail = I('post.partner_email','',"trim");
        $partnerInfo = M("users")->where(['email'=>$userEmail])->find();
        if(empty($partnerInfo) || $partnerInfo['is_partner']!=1){
            $result['status']=0;
            $result['msg']="转移用户非合作伙伴！";
            echo json_encode($result);
            exit;
        }
        if($partnerInfo['disabled']!=1){
            $result['status']=0;
            $result['msg']="此合作伙伴已被禁用！";
            echo json_encode($result);
            exit;
        }
        $count = M("user_address")->where(['user_id'=>$userId])->count("id");
        if($count == 0){
            $result['status']=0;
            $result['msg']="没有可转移客户！";
        }else{
            $moveRes = M("user_address")->where(['user_id'=>$userId])->save(['user_id'=>$partnerInfo['id']]);
            if($moveRes){
                $result['status']=1;
                $result['msg']="成功转移将".$count."个客户转移到[".$partnerInfo['first_name'].$partnerInfo['last_name']."]名下！";
            }else{
                $result['status']=0;
                $result['msg']="转移失败！";
            }
        }
        echo json_encode($result);
        exit;
    }
         
}